package com.zyz.bookborrowing.servlet;

import com.zyz.bookborrowing.bean.User;
import com.zyz.bookborrowing.service.IUserService;
import com.zyz.bookborrowing.service.UserServiceImpl;
import com.zyz.bookborrowing.utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "loginServlet", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        实现登录的功能
//        获取提交信息，Service方法处理，根据结果加以响应
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        User user = userService.checkUserNP(userName, password);
        HttpSession session = req.getSession();
        if (user != null){
//            将获取到的用户信息的密码置空，以防被从session里获取
            user.setPassword(null);
            session.setAttribute(Constant.SERVLET_LOGIN_USER, user);
//            登录成功
            resp.sendRedirect("/main.jsp");
        } else {

            session.setAttribute("msg", "账号密码错误");
            resp.sendRedirect("/login.jsp");
        }
    }
}
